<template>
  <div class="user-manage-container">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-card shadow="hover">
        <div class="search-wrapper">
          <el-input
              v-model="searchQuery"
              placeholder="输入用户名或手机号搜索"
              clearable
              class="search-input"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select v-model="statusFilter" placeholder="用户状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="正常" :value="1" />
            <el-option label="已禁用" :value="2" />
            <el-option label="待审核" :value="3" />
          </el-select>

          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>搜索
          </el-button>

          <el-button type="success" @click="handleAddUser" v-if="isAdmin">
            <el-icon><Plus /></el-icon>新增用户
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 用户表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table
          :data="filteredUserList"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column type="index" width="50" label="序号" />

        <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-avatar
                :size="40"
                :src="scope.row.avatar || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
            />
          </template>
        </el-table-column>

        <el-table-column prop="userName" label="用户名" width="120" />

        <el-table-column prop="realName" label="真实姓名" width="120">
          <template #default="scope">
            {{ scope.row.realName || '未设置' }}
          </template>
        </el-table-column>

        <el-table-column prop="phone" label="手机号" width="120" />

        <el-table-column prop="email" label="邮箱" width="180">
          <template #default="scope">
            {{ scope.row.email || '未设置' }}
          </template>
        </el-table-column>

        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender || '未设置' }}
          </template>
        </el-table-column>

        <el-table-column prop="exp" label="经验值" width="100" sortable />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getUserStatusType(scope.row.status)">
              {{ getUserStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" width="220">
          <template #default="scope">
            <el-button
                size="small"
                @click="handleViewUser(scope.row)"
                type="primary"
                link
            >
              查看
            </el-button>

            <el-button
                size="small"
                @click="handleEditUser(scope.row)"
                type="primary"
                link
                v-if="isAdmin"
            >
              编辑
            </el-button>

            <el-button
                size="small"
                @click="handleDeleteUser(scope.row)"
                type="danger"
                link
                v-if="isAdmin"
            >
              删除
            </el-button>

            <el-button
                size="small"
                @click="handleChangeStatus(scope.row)"
                :type="scope.row.status === 1 ? 'warning' : 'success'"
                link
                v-if="isAdmin"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalUsers"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增用户' : dialogType === 'edit' ? '编辑用户' : '用户详情'"
        width="600px"
    >
      <el-form
          ref="userFormRef"
          :model="userForm"
          :rules="userFormRules"
          label-width="100px"
          :disabled="dialogType === 'view'"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="userForm.userName" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input v-model="userForm.realName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="userForm.gender" placeholder="请选择性别">
                <el-option label="男" value="男" />
                <el-option label="女" value="女" />
                <el-option label="其他" value="其他" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="userForm.birthday"
                  type="date"
                  placeholder="选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经验值" prop="exp">
              <el-input-number v-model="userForm.exp" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="userForm.status" placeholder="请选择状态">
                <el-option label="正常" :value="1" />
                <el-option label="已禁用" :value="2" />
                <el-option label="待审核" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="/api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="个人简介" prop="bio">
          <el-input v-model="userForm.bio" type="textarea" rows="3" />
        </el-form-item>

        <el-form-item v-if="dialogType === 'add'" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitUserForm"
              v-if="dialogType !== 'view'"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
        v-model="deleteDialogVisible"
        title="确认删除"
        width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><WarningFilled /></el-icon>
        <span>确定要删除用户 <strong>{{ selectedUser.userName }}</strong> 吗？此操作不可恢复！</span>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, WarningFilled } from '@element-plus/icons-vue'
import {updateUser,deleteUser,getAllUser,addUser,changeUserStatus} from "@/api/user";

export default {
  name: 'UserManagement',
  components: {
    Search,
    Plus,
    WarningFilled
  },
  setup() {
    // 状态和数据
    const loading = ref(false);
    const userList = ref([]);
    const searchQuery = ref('');
    const statusFilter = ref('');
    const dialogVisible = ref(false);
    const dialogType = ref('view'); // 'view', 'add', 'edit'
    const deleteDialogVisible = ref(false);
    const selectedUser = ref({});
    const currentPage = ref(1);
    const pageSize = ref(10);
    const totalUsers = ref(0);

    // 管理员权限判断（实际项目中应该从登录用户信息或权限中获取）
    const isAdmin = ref(true); // 假设当前用户是管理员

    // 用户表单
    const userFormRef = ref(null);
    const userForm = reactive({
      userId: null,
      userName: '',
      realName: '',
      avatar: '',
      exp: 0,
      password: '',
      birthday: '',
      bio: '',
      phone: '',
      gender: '',
      email: '',
      status: 1
    });

    // 表单验证规则
    const userFormRules = reactive({
      userName: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在2到20个字符之间', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      email: [
        { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      password: [
        {
          validator: (rule, value, callback) => {
            if (dialogType.value === 'add' && !value) {
              callback(new Error('请输入密码'));
            } else {
              callback();
            }
          },
          trigger: 'blur'
        }
      ]
    });

    // 根据过滤条件筛选用户
    const filteredUserList = computed(() => {
      if (!userList.value) return [];

      return userList.value.filter(user => {
        const matchQuery = searchQuery.value
            ? (user.userName && user.userName.includes(searchQuery.value)) ||
            (user.phone && user.phone.includes(searchQuery.value)) ||
            (user.realName && user.realName.includes(searchQuery.value))
            : true;

        const matchStatus = statusFilter.value !== ''
            ? user.status === statusFilter.value
            : true;

        return matchQuery && matchStatus;
      });
    });

    // 获取用户状态对应的文本
    const getUserStatusText = (status) => {
      switch (status) {
        case 1: return '正常';
        case 2: return '已禁用';
        case 3: return '待审核';
        default: return '未知';
      }
    };

    // 获取用户状态对应的标签类型
    const getUserStatusType = (status) => {
      switch (status) {
        case 1: return 'success';
        case 2: return 'danger';
        case 3: return 'warning';
        default: return 'info';
      }
    };

    // 获取用户列表
    const fetchUserList = async () => {
      loading.value = true;
      try {
        const { state, message, data } = await getAllUser();
        if (state === 0 && data) {
          userList.value = data;
          totalUsers.value = data.length;
        } else {
          ElMessage.error(message || '获取用户列表失败');
        }
      } catch (error) {
        console.error('获取用户列表出错:', error);
        ElMessage.error('获取用户列表失败');
      } finally {
        loading.value = false;
      }
    };

    // 搜索用户
    const handleSearch = () => {
      currentPage.value = 1;
      // 实际项目中可能需要调用接口进行搜索，这里只是前端过滤
    };

    // 变更每页显示数量
    const handleSizeChange = (val) => {
      pageSize.value = val;
      // 如果是服务端分页，这里需要重新请求数据
    };

    // 变更当前页码
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      // 如果是服务端分页，这里需要重新请求数据
    };

    // 查看用户
    const handleViewUser = (row) => {
      selectedUser.value = row;
      Object.assign(userForm, JSON.parse(JSON.stringify(row)));
      dialogType.value = 'view';
      dialogVisible.value = true;
    };

    // 编辑用户
    const handleEditUser = (row) => {
      selectedUser.value = row;
      Object.assign(userForm, JSON.parse(JSON.stringify(row)));
      // 格式化日期
      if (userForm.birthday && typeof userForm.birthday === 'string' && userForm.birthday.includes('T')) {
        userForm.birthday = userForm.birthday.split('T')[0];
      }
      dialogType.value = 'edit';
      dialogVisible.value = true;
    };

    // 添加用户
    const handleAddUser = () => {
      Object.keys(userForm).forEach(key => {
        if (key !== 'status' && key !== 'exp') {
          userForm[key] = '';
        }
      });
      userForm.status = 3; // 默认为待审核状态
      userForm.exp = 0;
      dialogType.value = 'add';
      dialogVisible.value = true;
    };

    // 删除用户
    const handleDeleteUser = (row) => {
      selectedUser.value = row;
      deleteDialogVisible.value = true;
    };

    // 确认删除
    const confirmDelete = async () => {
      loading.value = true;
      try {
        const { state, message } = await deleteUser(selectedUser.value.userId);
        if (state === 0) {
          ElMessage.success('删除成功');
          deleteDialogVisible.value = false;
          // 从列表中移除
          const index = userList.value.findIndex(item => item.userId === selectedUser.value.userId);
          if (index !== -1) {
            userList.value.splice(index, 1);
          }
        } else {
          ElMessage.error(message || '删除失败');
        }
      } catch (error) {
        console.error('删除用户出错:', error);
        ElMessage.error('删除失败');
      } finally {
        loading.value = false;
      }
    };

    // 修改用户状态
    const handleChangeStatus = async (row) => {
      const newStatus = row.status === 1 ? 2 : 1;
      const statusText = newStatus === 1 ? '启用' : '禁用';

      try {
        const { state, message } = await changeUserStatus(row.userId, newStatus);
        if (state === 0) {
          ElMessage.success(`${statusText}成功`);
          // 更新状态
          row.status = newStatus;
        } else {
          ElMessage.error(message || `${statusText}失败`);
        }
      } catch (error) {
        console.error(`${statusText}用户出错:`, error);
        ElMessage.error(`${statusText}失败`);
      }
    };

    // 提交用户表单
    const submitUserForm = async () => {
      if (!userFormRef.value) return;

      await userFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          try {
            const apiFunc = dialogType.value === 'add' ? addUser : updateUser;
            const { state, message } = await apiFunc(userForm);

            if (state === 0) {
              ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功');
              dialogVisible.value = false;

              if (dialogType.value === 'add') {
                // 模拟添加到列表
                const newUser = { ...userForm, userId: Date.now() }; // 模拟生成ID
                userList.value.unshift(newUser);
              } else {
                // 更新列表中的数据
                const index = userList.value.findIndex(item => item.userId === userForm.userId);
                if (index !== -1) {
                  userList.value[index] = { ...userList.value[index], ...userForm };
                }
              }
            } else {
              ElMessage.error(message || (dialogType.value === 'add' ? '添加失败' : '更新失败'));
            }
          } catch (error) {
            console.error(dialogType.value === 'add' ? '添加用户出错:' : '更新用户出错:', error);
            ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败');
          } finally {
            loading.value = false;
          }
        }
      });
    };

    // 头像上传成功回调
    const handleAvatarSuccess = (response, file) => {
      // 假设上传接口返回的格式是 { state: 0, data: { url: '图片地址' } }
      if (response.state === 0 && response.data) {
        userForm.avatar = response.data.url;
        ElMessage.success('头像上传成功');
      } else {
        ElMessage.error('头像上传失败');
      }
    };

    // 头像上传前的验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        ElMessage.error('头像只能是JPG或PNG格式!');
        return false;
      }
      if (!isLt2M) {
        ElMessage.error('头像大小不能超过2MB!');
        return false;
      }
      return true;
    };

    // 生命周期钩子
    onMounted(() => {
      fetchUserList();
    });

    return {
      loading,
      userList,
      searchQuery,
      statusFilter,
      dialogVisible,
      dialogType,
      deleteDialogVisible,
      selectedUser,
      currentPage,
      pageSize,
      totalUsers,
      isAdmin,
      userFormRef,
      userForm,
      userFormRules,
      filteredUserList,
      getUserStatusText,
      getUserStatusType,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      handleViewUser,
      handleEditUser,
      handleAddUser,
      handleDeleteUser,
      confirmDelete,
      handleChangeStatus,
      submitUserForm,
      handleAvatarSuccess,
      beforeAvatarUpload
    };
  }
};
</script>

<style scoped>
.user-manage-container {
  padding: 20px;
}

.operation-area {
  margin-bottom: 20px;
}

.search-wrapper {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 220px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #E6A23C;
}
</style>